package sk.marek.barak.server;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.memcache.Expiration;
import com.google.appengine.api.memcache.MemcacheService;
import com.google.appengine.api.memcache.MemcacheServiceFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserServiceFactory;

public class MessageGAEDAO implements MessageDAO {

private static Expiration expiration = Expiration.byDeltaSeconds(60);
	
	@Override
	public void sendMessage(String userId, String message) {
		MemcacheService cache = MemcacheServiceFactory.getMemcacheService();
		User curent = UserServiceFactory.getUserService().getCurrentUser();
		Key parent = KeyFactory.createKey("User",userId);
		Key key = KeyFactory.createKey(parent, "Message", curent.getUserId());
		String value = (String)cache.get(key);
		if(value!=null){
			message = message+" "+value;
		}
		cache.put(key, message,expiration);
	}

	@Override
	public String getMessage(String userId) {
		MemcacheService cache = MemcacheServiceFactory.getMemcacheService();
		User curent = UserServiceFactory.getUserService().getCurrentUser();
		Key parent = KeyFactory.createKey("User", curent.getUserId());
		Key key = KeyFactory.createKey(parent,"Message",userId);
		
		String message =(String)cache.get(key);
		
		if(message!=null){
			cache.delete(key);
		}
		return message;
	}

}
